<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <el-form label-width="80px" :inline="true" size="normal">
            <el-form-item>
                <el-input placeholder="用户名" v-model="tmSearch.username"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button  type="primary" icon="el-icon-search" @click="SearchData" :disabled="!tmSearch.username">查询</el-button>
                <el-button  @click="clear">清空</el-button>
            </el-form-item>
        </el-form>

        <el-button type="primary" v-if="$hasBP('btn.User.add')" size="default" @click="addData">添加</el-button>
        <el-button type="danger" v-if="$hasBP('btn.User.remove')" size="default" @click="delAllData">批量删除</el-button>

        <el-table border  v-loading="loading" stripe style="margin-top:20px" :data="userList.items">
            <el-table-column type="selection" width="55" @selection-change="handleSelectionChange"> </el-table-column>
            <el-table-column label="序号" width="80" type="index"> </el-table-column>
            <el-table-column label="用户名" width="150" prop="username"> </el-table-column>
            <el-table-column label="用户昵称" prop="nickName"> </el-table-column>
            <el-table-column label="角色列表" prop="roleName"> </el-table-column>
            <el-table-column label="创建时间" width="180" prop="gmtCreate"> </el-table-column>
            <el-table-column label="更新时间" width="180" prop="gmtModified"> </el-table-column>
            <el-table-column label="操作" width="230">
                <template slot-scope="{row,$index}">
                    <el-button type="info" v-if="$hasBP('btn.User.assgin')" size="small" icon="el-icon-user-solid" @click="roleData(row)"></el-button>
                    <el-button type="primary" v-if="$hasBP('btn.User.update')" size="small" icon="el-icon-edit" @click="upData(row)"></el-button>
                    <el-button type="danger"  v-if="$hasBP('btn.User.remove')" size="small" icon="el-icon-delete-solid " @click="delData(row)">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination @size-change="handlersize" @current-change="getuserList" style="margin-top:20px"
            :page-sizes="[3, 5, 7, 9]" :current-page="currentPage" :page-size="pageSize"
            layout="prev, pager, next, jumper, ->, sizes, total" :total="userList.total">
        </el-pagination>


        <!-- 添加或修改对话框 -->

        <el-dialog title="添加用户" :visible.sync="dialogVisible">
            <el-form :model="form" ref="form" :rules="rules" label-width="120px" :inline="false" size="normal">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="form.nickName"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" type="password" prop="password" v-show="!form.id">
                    <el-input v-model="form.password"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="addoRupdata">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 用户角色分配 -->
        <el-dialog title="设置角色" :visible.sync="roledialog">
            <el-form label-width="120px">
                <el-form-item label="用户名">
                    <el-input autocomplete="off" disabled :value="form.username"></el-input>
                </el-form-item>
                <el-form-item label="用户列表">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                    </el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="userRoleIds" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(item,index) in allRolesList" :label="item.id" :key="item.id">
                            {{item.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roledialog = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </div>
        </el-dialog>
    </el-card>

</template>

<script>

export default {
    data() {
        return {
            // 加载效果
            loading:false,
            // 第几页
            currentPage: 1,
            // 每页条数
            pageSize: 3,
            // 搜索的值
            searchObj: {
                username: ''
            },
            // 收集的值
            tmSearch: {
                username: ''
            },
            // 列表数据
            userList: {},
            // 添加或修改对话框标识
            dialogVisible: false,
            // 收集表单值
            form: {
                username: '',
                nickName: '',
                password: ''
            },
            // 表单验证
            rules: {
                username: [
                    { required: true, message: '添加的名称不能为空', trigger: 'blur' },
                    { min: 3, message: '长度不能小于三个', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                    { min: 6, message: '长度不能小于六个', trigger: 'blur' }
                ],
            },
            // 角色详情
            roledialog: false,
            // 不确定状态
            isIndeterminate: true,
            // 全选状态
            checkAll: false,
            // 已有角色的id
            userRoleIds: [],
            // 角色信息
            allRolesList: [],
            // 当前列选中的数据
            selectedAll: []
        }
    },
    mounted() {
        // 挂载时调用
        this.getuserList()
    },
    methods: {
        //获取列表数据
        async getuserList(page = 1) {
            this.loading=true
            this.currentPage = page
            const result = await this.$API.user.getPageList(this.currentPage, this.pageSize, this.searchObj)
            //    console.log(result);
            this.userList = result.data
            this.loading=false
        },
        // 点击切换一页几条数据
        handlersize(page) {
            this.pageSize = page
            // 刷新页面
            this.getuserList()
        },
        // 点击查询按钮
        SearchData() {
            // 将搜索到的值赋值给搜索参数
            this.searchObj = { ...this.tmSearch }
            //刷新页面
            this.getuserList()
        },
        // 点击取消按钮，重置搜索框
        clear() {
            // 搜索的值
            this.searchObj.username=''
             // 收集的值
            this.tmSearch.username=''
            this.getuserList()

        },
        // 点击添加按钮
        addData() {
            this.dialogVisible = true
            // 清空表单数据
            this.form = {
                username: '',
                nickName: '',
                password: ''
            }

            this.$nextTick(() => {
                this.$refs.form.clearValidate()
            })
        },
        // 点击修改按钮
        upData(row) {
            this.dialogVisible = true
            this.form = { ...row }
        },
        // 点击取消按钮
        cancel() {
            this.dialogVisible = false
            // 清空表单数据
            this.form = {
                username: '',
                nickName: '',
                password: ''
            }
        },
        // 点击确定按钮
        addoRupdata() {
            this.$refs['form'].validate(async (val) => {
                // 表单验证
                if (val) {
                    const user = { ...this.form }
                    if (user.id) {
                        await this.$API.user.update(user)
                    } else {
                        await this.$API.user.add(user)
                    }
                    this.$message({
                        message: user.id ? '修改成功' : '添加成功',
                        type: 'success'
                    });
                    // 刷新页面
                    this.getuserList()
                    // 关闭对话框
                    this.dialogVisible = false
                    // 清空表单数据
                    this.form = {
                        username: '',
                        nickName: '',
                        password: ''
                    }
                } else {
                    this.$message.danger(user.id ? '修改失败' : '添加失败')
                }
            })
        },
        // 点击删除按钮
        delData(row) {

            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$API.user.removeById(row.id)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                // 刷新页面
                this.getuserList(this.currentPage)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 点击查看角色按钮
        async roleData(row) {
            this.roledialog = true
            // 获取用户名
            this.form = { ...row }
            // 获取用户信息
            const result = await this.$API.user.getRoles(row.id)
            console.log(result);
            const { allRolesList, assignRoles } = result.data
            //所有角色信息
            this.allRolesList = allRolesList
            this.userRoleIds = assignRoles.map(item => item.id)

            this.isIndeterminate = this.userRoleIds.length > 0 && this.allRolesList.length > this.userRoleIds.length

            this.checkAll = this.userRoleIds.length === this.allRolesList.length && this.allRolesList.length != 0
        },
        // 点击全选复选框
        handleCheckAllChange(val) {
            console.log(val);
            //  val布尔值   判断已有角色数组是否有值
            this.userRoleIds = val ? this.allRolesList.map(item => item.id) : []
            this.isIndeterminate = this.userRoleIds.length > 0 && this.allRolesList.length > this.userRoleIds.length
        },
        // 点击复选框
        handleCheckedCitiesChange(val) {
            // console.log(val);
            const count = val.length
            this.checkAll = count === this.allRolesList.length && this.allRolesList.length > 0
            this.isIndeterminate = count > 0 && this.allRolesList.length > count
        },
        // 点击确定按钮提交修改的角色列表
        async addRole() {
            const roleId = this.userRoleIds.join(',')
            try {
                await this.$API.user.assignRoles(this.form.id, roleId)
                this.$message({
                    message: '提交成功',
                    type: 'success'
                });
                this.getuserList(this.currentPage)
                this.roledialog = false

            } catch (error) {
                this.$message({
                    message: '提交失败',
                    type: 'danger'
                });
            }

        },
        // 监听当前列全部选中的数据
        handleSelectionChange(val) {
            //  val当前列选中的每一项
            this.selectedAll = val
        },
        // 点击批量删除
        async delAllData() {
            try {
                await this.$API.user.removeUsers(this.selectedAll)
                this.$message({
                    message: '批量删除成功',
                    type: 'success'
                });
                this.getuserList(this.currentPage)
            } catch (error) {
                this.$message({
                    message: '批量删除失败',
                    type: 'danger'
                });
            }
        }

    },

}
</script>

<style  scoped>

</style>